/*  
 * i-OSGi - Tunable Bundle Isolation for OSGi
 * Copyright (C) 2011  Sven Schulz
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.iosgi.impl;

import java.net.URI;

import org.iosgi.Constants;

/**
 * @author Sven Schulz
 */
public class EnvironmentIDs {

	public static URI getEnvironmentId(int level) {
		String raw = System.getProperty(Constants.ENVIRONMENT_ID);
		if (raw == null) {
			raw = "/0/0";
		}
		StringBuilder b = new StringBuilder();
		String[] parts = raw.split("/");
		for (int i = 0; i <= level; i++) {
			b.append('/').append(parts[i + 1]);
		}
		return URI.create(b.toString());
	}

	public static boolean isDestructible(URI id) {
		return !id.toString().endsWith("/0");
	}

	public static long[] dissect(final URI id) {
		String s = id.toString();
		if (s.equals("/")) {
			return new long[0];
		}
		String[] tokens = s.split("/");
		long[] parts = new long[tokens.length - 1];
		for (int i = 1; i < tokens.length; i++) {
			parts[i - 1] = Long.parseLong(tokens[i]);
		}
		return parts;
	}

	public static long getLastPart(final URI id) {
		long[] parts = dissect(id);
		return parts[parts.length - 1];
	}

	public static int getLevel(final URI id) {
		return dissect(id).length;
	}

	public static URI getParent(URI id) {
		long[] parts = dissect(id);
		if (parts.length == 0) {
			return null;
		}
		StringBuilder b = new StringBuilder();
		if (parts.length == 1) {
			return URI.create("/");
		} else {
			for (int i = 0; i < parts.length - 1; i++) {
				b.append('/').append(parts[i]);
			}
			return URI.create(b.toString());
		}
	}

}